#include "rasterization.h"
#include "sdl_auxiliary.h"
#include "sdl_screen.h"
#include "settings.h"


Rasterization::Rasterization() throw (sdl::Exception)
: _camera(CAMERA_POSITION, CAMERA_FOCAL_LEN)
, _ishader(glm::vec3(1), glm::vec3(0.2))
{
	_scene.generateDefault();
	sdl::Screen* s = sdl::Screen::getInstance();
	s->setCaption("Rasterization");
	// Register callbacks
	s->addListener(this);
	sdl::Event::getInstance()->addListener(this);
	// Update on start
	s->update();
	// Enter main loop
	sdl::Event::getInstance()->wait();
	// Get a screenshot
	s->saveBmp("screenshot.bmp");
}


void Rasterization::on(sdl::SurfaceListener::Update, sdl::Surface* s) throw()
{
	s->fill(NULL, 0);

	Triangle::cIter i = _scene.getTriangles().begin();
	for (; i != _scene.getTriangles().end(); ++i) {
		//(*i)->drawEdges(s, _camera.getVertexShader(), _ishader);
		//(*i)->drawFilled(s, _camera.getVertexShader(), ColorShader((*i)->getColor()));
		(*i)->drawFilled(s, _camera.getVertexShader());
	}
}


void Rasterization::on(sdl::EventListener::NewEvent, const SDL_Event* e) throw()
{
	if (e->type == SDL_QUIT ||
		(e->type == SDL_KEYDOWN && e->key.keysym.sym == SDLK_ESCAPE))
	{
		sdl::Event::getInstance()->stopWaiting();
	}
}


int main()
{
	try {
		// Init SDL library
		sdl::initialize();
		// Create window
		sdl::Screen::getInstance()->setVideoMode(
			SCREEN_WIDTH, SCREEN_HEIGHT, USE_DEPTH_BUFFER);
		Rasterization();
	}
	catch (sdl::Exception& e) {
		// Get rid off warning (format not a string literal
		// and no format arguments)
		fprintf(stderr, "%s", e.what());
		return 1;
	}
	return 0;
}

